In [1]:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
In [2]:
#import setuptools
%load_ext Cython
In [3]:
%%cython
cdef f1(int x):
return x*x
cpdef f2(int x):
return x*x
cpdef f3(int x):
return f1(x)
In [4]:
#dir()
In [5]:
f2(3)
Out[5]:
f1 is not visible since defined via "cdef"
In [7]:
f1(3)
In [8]:
f3(3)
Out[8]:
In [9]:
%%cython
cpdef fibseq(float[:] x):
cdef int n
cdef int i
n = len(x)
x[0] = 1.
x[1] = 1.
for i in range(2,n):
x[i] = x[i-1]+x[i-2]
In [11]:
x = np.zeros((43,), np.float32)
In [12]:
fibseq(x)
In [13]:
x
Out[13]:
In [14]:
ratio = x[0:-1]/x[1:]
In [16]:
plt.plot(ratio,'.');
In [17]:
(np.sqrt(5)-1)/2.
Out[17]:
In [18]:
plt.semilogy(ratio-(np.sqrt(5)-1)/2,'.');
In [19]:
ratio
Out[19]:
In [20]:
import seaborn as sbs
In [21]:
sbs.plt.plot(ratio)
Out[21]:
In [22]:
def pyfib(n):
a,b = 1,1
for i in range(n):
a,b = a+b, a
return a
In [23]:
pyfib(5)
Out[23]:
In [24]:
%%cython
def fib(int n):
cdef int i,a,b
a,b = 1,1
for i in range(n):
a,b = a+b, a
return a
In [25]:
fib(10)
Out[25]:
In [26]:
[fib(i) for i in range(10)]
Out[26]:
In [27]:
pyfib(10)
Out[27]:
In [28]:
%timeit fib(10)
%timeit pyfib(10)
In [29]:
%%cython
cpdef float distance(float[:] x, float[:] y):
cdef int i
cdef int n = x.shape[0]
cdef float d = 0.0
for i in range(n):
d += (x[i]-y[i])**2
return d
In [30]:
import numpy as np
x = np.array([1,2,3], np.float32)
y = np.array([7,6,5], np.float32)
dist = distance(x,y)
print dist
In [31]:
def pydistance(x, y, n):
d = 0.0
for i in range(n):
d += (x[i]-y[i])**2
return d
In [32]:
%timeit distance(x,y)
%timeit pydistance(x,y,3)
In [ ]: